#define _CRT_SECURE_NO_WARNINGS 1

#include "List.h"

ListNode* ListCreate(LTDataType x)
{
	ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
	newNode->data = x;
	newNode->next = NULL;
	newNode->prev = NULL;
	return newNode;
}

ListNode* ListInit(ListNode* plist)
{
	plist = (ListNode*)malloc(sizeof(ListNode));
	plist->next = plist;
	plist->prev = plist;
	return plist;
}

void ListPrint(ListNode* plist)
{
	assert(plist);
	ListNode* current = plist->next;
	while (current != plist)
	{
		printf("%d ", current->data);
		current = current->next;
	}
	printf("\n");
}


void ListPushBack(ListNode* plist, LTDataType x)
{
	/*assert(plist);
	ListNode* newNode = ListCreate(x);
	ListNode* tail = plist->prev;
	tail->next = newNode;
	newNode->prev = tail;
	newNode->next = plist;
	plist->prev = newNode;*/

	ListInsert(plist, x);
}


void ListPopBack(ListNode* plist)
{
	/*assert(plist);
	assert(plist->next != plist);
	ListNode* tail = plist->prev;
	ListNode* tailPrev = tail->prev;
	tailPrev->next = plist;
	plist->prev = tailPrev;
	free(tail);
	tail->next = NULL;
	tail->prev = NULL;*/

	ListErase(plist->prev);
}

void ListPopFront(ListNode* plist)
{
	/*assert(plist);
	assert(plist->next != plist);
	ListNode* next = plist->next;
	ListNode* nextNext = next->next;
	plist->next = nextNext;
	nextNext->prev = plist;
	free(next);
	next->next = NULL;
	next->prev = NULL;*/

	ListErase(plist->next);
}

void ListPushFront(ListNode* plist, LTDataType x)
{
	/*assert(plist);
	ListNode* newNode = ListCreate(x);
	ListNode* next = plist->next;
	plist->next = newNode;
	newNode->prev = plist;
	newNode->next = next;
	next->prev = newNode;*/

	ListInsert(plist->next, x);

}


void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newNode = ListCreate(x);
	ListNode* posPrev = pos->prev;
	posPrev->next = newNode;
	newNode->prev = posPrev;
	newNode->next = pos;
	pos->prev = newNode;
}


void ListErase(ListNode* pos)
{
	assert(pos);
	assert(pos->next != pos);
	ListNode* posPrev = pos->prev;
	ListNode* posNext = pos->next;
	posPrev->next = posNext;
	posNext->prev = posPrev;

	free(pos);
	pos->next = NULL;
	pos->prev = NULL;
}


void ListDestory(ListNode* plist)
{
	assert(plist);
	ListNode* current = plist->next;
	while (current != plist)
	{
		ListNode* next = current->next;
		free(current);
		current = next;
		
	}
	free(plist);
}

